package com.ogawa.jopai.devicemanage.viewmodel

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.ogawa.base.base.BaseViewModel
import com.ogawa.base.bean.LoadState
import com.ogawa.projectcommon.utils.dataConvert
import com.ogawa.projectcommon.utils.launch
import com.ogawa.jopai.devicemanage.bean.*
import com.ogawa.projectcommon.network.RetrofitManager
import com.ogawa.jopai.devicemanage.service.MassageApiService
import com.ogawa.projectcommon.utils.ProjectSpUtils
import kotlinx.coroutines.cancel

class MessageViewModel : BaseViewModel() {
    internal val mGetDeviceShareResponseList = MutableLiveData<List<GetDeviceShareResponse>>()
    internal val mPutDeviceShareResponse = MutableLiveData<PutDeviceShareResponse>()

    fun getDeviceShare() {
        launch({
            val userInfo = ProjectSpUtils.getUserInfo()
            loadState.value = LoadState.Loading("")
            mGetDeviceShareResponseList.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                .getDeviceShare(userInfo.user.id)
                .dataConvert()

            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }
    fun putDeviceShare(request: PutDeviceShareRequest) {
        launch({
            val userInfo = ProjectSpUtils.getUserInfo()
            loadState.value = LoadState.Loading("")
            mPutDeviceShareResponse.value = RetrofitManager.INSTANCE.createService(MassageApiService::class.java)
                .putDeviceShare(request)
                .dataConvert()

            loadState.value = LoadState.Success("")
        }
            , { loadState.value = LoadState.Fail(it.message ?: "") }
            , {})
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun ondestory() {
        LogUtils.e("ON_DESTROY")
        viewModelScope.cancel()
    }

}
